package io.xxx.omni.osc.sync

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.dateTimeFormatter
import io.xxx.omni.osc.common.toJSONObject
import io.xxx.omni.osc.common.toLocalDateTime
import io.xxx.omni.osc.domain.Document
import io.xxx.omni.osc.domain.DocumentType
import io.xxx.omni.osc.domain.PlatformIdentity
import io.xxx.omni.osc.sdk.DxysClient
import org.springframework.stereotype.Component
import java.time.LocalDateTime

/**
 * 丁香医生
 */
abstract class DxysPorter : GenericPageDocumentPorter(), PlatformIdentity.DingXiangYiSheng {

    protected abstract val method: String

    override fun getResponse(context: JobContext, pageNo: Int, hasTotal: Boolean): JSONObject {
        val (store, startTime, endTime) = context
        val request = buildRequest(startTime, endTime, pageNo)
        val client = applicationContext.getBean(DxysClient::class.java)
        val response = client.execute(store, method, request)
        if (!response.getString("code").equals("0")) {
            throwException(context, method, response)
        }
        return response
    }

    protected abstract fun buildRequest(
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        pageNo: Int
    ): Map<String, Any>
}

@Component
class DxysTradePorter : DxysPorter() {

    override val documentType = DocumentType.TRADE

    override val method = "Differ.JH.Business.GetOrder"

    override fun getCount(context: JobContext, response: JSONObject): Int = response.getInteger("numtotalorder")

    override fun buildDocuments(context: JobContext, response: JSONObject): List<Document> {
        return response
            .getJSONArray("orders")
            .map {
                val value = it.toJSONObject()
                val sn = value.getString("PlatOrderNo")
                val status = value.getString("status")
                val modified = value.getString("tradetime").toLocalDateTime()
                Document(sn, status, modified, value)
            }
    }

    override fun buildRequest(startTime: LocalDateTime, endTime: LocalDateTime, pageNo: Int): Map<String, Any> {
        return mapOf(
            "OrderStatus" to "JH_99",
            "TimeType" to "JH_01",
            "StartTime" to startTime.format(dateTimeFormatter),
            "EndTime" to endTime.format(dateTimeFormatter),
            "PageIndex" to pageNo,
            "PageSize" to pageSize,
        )
    }
}